package com.authorization.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.oauth2.provider.token.TokenStore;
import org.springframework.security.oauth2.provider.token.store.InMemoryTokenStore;

/**
 * @description: spring security 的配置
 * @Author C_Y_J
 * @create 2022/1/7 14:53
 **/
@Configuration
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    /**
     * 密码编码解码器
     * 在使用对比密码时候需要
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }

    /**
     * TokenStore 令牌存储服务（令牌存储在哪个地方？内存，redis,MySQL）
     *
     * @return
     */
    @Bean
    public TokenStore inMemoryTokenStore() {
        return new InMemoryTokenStore();
    }


    /**
     * 身份认证管理器：在使用grant_type=password的时候就要用到
     *
     * @return
     * @throws Exception
     */
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }


//    @Override
//    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
//        // 添加一个用户、保存在内存中
//        auth.inMemoryAuthentication()
//                .withUser("user")
//                .password(passwordEncoder().encode("123456"))
//                .authorities(Collections.emptyList());
//
//    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        // 所有请求都需要通过认证
        http.authorizeRequests()
                .anyRequest().authenticated();
        // 允许Basic登录
        http.httpBasic();
        // 关跨域保护
        http.csrf().disable();
    }

}
